<template>
  <div>
    <!-- head -->
    <h1>捐赠管理</h1>

    <!-- search part start-->
    <search-part
      :org-list="orgList"
      :total-page="totalPage"
      :current-page="currentPage"
      @change-data-filter="handleChange"
    ></search-part>
    <!-- search part end-->

    <!-- add item part start -->
    <add-part :org-list="orgList" @onclick="addMoneyList" />
    <!-- add item part end -->

    <!-- table part start -->
    <base-table :tbData="showList">

    <!-- slot for table head start -->
      <template #head>
        <tr>
          <th>全选<input type="checkbox" v-model="checkAll" /></th>
          <th>序号</th>
          <th>捐赠人</th>
          <th>受捐企业</th>
          <th>金额</th>
          <th>受捐日期</th>
          <th>操作</th>
        </tr>
      </template>
    <!-- slot for table head end -->

    <!-- slot for table body start -->
      <template #body="row">
        <td> 

          <!-- all check input -->
          <input type="checkbox" v-model="row.item.isSelect" />
        </td>

        <!-- if none of items is on modify state , display the text  -->
        <template v-if="!onModifyState(row.item.id)">
          <td v-text="row.index + 1"></td>
          <td v-text="row.item.pname"></td>
          <td v-text="orgIdToOrgName(row.item.orgId)"></td>
          <td v-text="row.item.money"></td>
          <td v-text="row.item.date"></td>
          <td>
            <a href="javascript:;" @click="removeMoneyList(row.item.id)"
              >删除</a
            >
            &nbsp;
            <a href="javascript:;" @click="modifyMoneyList(row.item)">修改</a>
          </td>
        </template>
    <!-- slot for table body end -->

        <!-- else display the modified inputs start -->
        <template v-else>
          <td v-text="row.index + 1"></td>
          <td>
            <input type="text" v-model.trim="pname" />
          </td>
          <td>

            <!-- the select component start-->
            <base-select
              :defaultOption="+row.item.orgId"
              :lists="orgList"
              @selected="getOption"
            >
              <template v-slot="option">
                {{ option.item.name }}
              </template>
            </base-select>
            <!-- the select component start-->

          </td>
          <td>
            <input type="text" v-model.trim.number="money" />
          </td>
          <td>
            <input type="text" v-model.trim="date" />
          </td>
          <td>
            <a href="javascript:;" @click="confirmModify(row.item.id)">确定</a>
            &nbsp;
            <a href="javascript:;" @click="cancelModify">取消</a>
          </td>
        </template>
        <!-- else display the modified inputs end -->

      </template>
      <!-- slot for table body end -->

    </base-table>
    <!-- table part end -->
    
  </div>
</template>

<script>
import SearchPart from "@/views/SearchPart";
import AddPart from "@/views/AddPart";
import EventBus from "@/EventBus";

//NONE means select all or none is onModifyState
const NONE = -1;

//localStorage key for moneylist
const LOCAL_MONEY = "dona-sadqioklasdhlhasdla";

//max number of items on every page
const PAGE_SIZE = 6;

//first page
const FIRST_PAGE=1;
export default {
  components: {
    SearchPart,
    AddPart,
    EventBus,
  },
  data() {
    return {
      moneyList: [],
      orgList: [],
      currentPage: FIRST_PAGE,
      onModifyId: NONE,
      
      //filter for searching
      dataTableFilter: NONE,
      pname: "",
      money: "",
      date: "",
      selectOption: "",
      localToken: LOCAL_MONEY,
    };
  },
  created() {
    // console.log(this.$db.listMoney);
    this.moneyList = this.$db.listMoney;
    this.orgList = this.$db.listOrgs;

    //EventBus for crossing-components comunication
    EventBus.$on("next", (num) => (this.currentPage += num));
    EventBus.$on("prev", (num) => (this.currentPage -= num));
  },
  computed: {

    //array of data for showing on the table 
    showList() {

      /**
       * thisPageTop means the upper bound of data index in this page
       * thisPageBottom means the lower bound of data index in this page
       * */
      const thisPageTop = this.currentPage * PAGE_SIZE;
      const thisPageBottom = (this.currentPage - 1) * PAGE_SIZE;

      //return item which index between top and bottom
      return this.tableList.filter(
        (ele, index) => index < thisPageTop && index >= thisPageBottom
      );
    },

    //return item be searched
    tableList() {
      return this.moneyList.filter(
        (ele) => this.dataTableFilter == -1 || ele.orgId == this.dataTableFilter
      );
    },

    //set check-all
    checkAll: {
      set(val) {
        this.tableList.forEach((ele) => (ele.isSelect = val));
      },
      get() {
        return this.tableList.every((ele) => ele.isSelect);
      },
    },

    //return number of pages
    totalPage() {
      const total = parseInt((this.tableList.length - 1) / PAGE_SIZE) + 1;
      if (this.currentPage > total) this.currentPage--;
      return total;
    },
  },
  watch: {

    //watch the moneyList for localStorage
    moneyList: {
      deep: true,
      handler: function (val) {
        localStorage.setItem(this.localToken, JSON.stringify(val));
      },
    },
  },
  methods: {

    //get the select option
    getOption(option) {
      this.selectOption = +option;
    },

    //parse orgId to orgName for showing
    orgIdToOrgName(id) {
      return this.orgList.find((ele) => ele.id == id).name;
    },

    addMoneyList(obj) {
      this.moneyList.addObj(obj);
      alert("添加成功！");
    },

    removeMoneyList(id) {
      this.moneyList.deleteById(id);
    },

    modifyMoneyList(item) {
      this.onModifyId = item.id;
      this.pname = item.pname;
      this.money = item.money;
      this.date = item.date;
      this.selectOption = item.orgId;
    },

    //set modify state by id
    onModifyState(id) {
      return id == this.onModifyId;
    },

    //save the modified data
    confirmModify(id) {
      if (!this.isCompleteData()) {
        alert("请确认信息的完整性！");
        return;
      }
      const item = {
        pname: this.pname,
        orgId: this.selectOption,
        money: this.money,
        date: this.date,
        id,
      };
      this.moneyList.modify(item);

      //reset modify state pointer
      this.onModifyId = NONE;
    },

    //reset modify state pointer
    cancelModify() {
      this.onModifyId = NONE;
    },

    //handle the search event
    handleChange(option) {
      this.dataTableFilter = +option;
    },
  },
};
</script>

<style>
</style>